//
//  WPMainViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/3/6.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "WPMainViewController.h"
#import "WPDataMap.h"
#import "WPWaveView.h"
#import "WPFilterCell.h"

#define kTextBGColor UIColorMakeWithHex(@"e5e5e5")

@interface WPMainViewController ()<GizWifiDeviceDelegate, WPFilterCellDelegate>
@property(nonatomic, strong) GizWifiDevice *model;
@property(nonatomic, strong) WPDataMap *dataMap;
@property(nonatomic, strong) UIView *headerView;
@property(nonatomic, strong) UIImageView *imageView;
@property(nonatomic, strong) QMUILabel *levelLabel;
@property(nonatomic, strong) QMUILabel *statusLabel;
@property(nonatomic, strong) UIImageView *imageView2;
@property(nonatomic, strong) QMUIButton *powerBtn;
@property(nonatomic, strong) QMUIButton *waterBtn;
@property(nonatomic, strong) UIView *offView;
@property(nonatomic, strong) WPWaveView *waveView;
@property(nonatomic, strong) UIImageView *imageView3;
@property(nonatomic, strong) UIView *backView;
@property(nonatomic, strong) QMUILabel *filterLabel;
@property(nonatomic, strong) QMUILabel *sumLabel;
@property(nonatomic, strong) NSIndexPath *editingIndexPath;
@property(nonatomic, strong) UIColor *mainColor;

@property(nonatomic, strong) NSString *filterAlertString;
@property(nonatomic, strong) QMUIAlertController *filterAlert;
@end

@implementation WPMainViewController

#pragma mark - overider

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (instancetype)initWithModel:(GizWifiDevice *)model {
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        self.model = model;
        self.model.delegate = self;
        _filterAlertString = @"";
    }
    return self;
}

-(void)initTableView {
    [super initTableView];
    
    self.view.backgroundColor = UIColorMakeWithHex(@"eeefef");
    
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _backView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.tableView.backgroundView = _backView;
    
    CGFloat contentMinY = self.qmui_navigationBarMaxYInViewCoordinator;
    if (IS_35INCH_SCREEN) {
        contentMinY = 64.0f;
    }
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - contentMinY)];
    _headerView.backgroundColor = UIColorWhite;
    self.tableView.tableHeaderView = _headerView;
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imageView.backgroundColor = UIColorClear;
    _imageView.image = UIImageMake(@"water_level_1");
    [_headerView addSubview:_imageView];
    
    _levelLabel = [[QMUILabel alloc] init];
    _levelLabel.backgroundColor = kTextBGColor;
    _levelLabel.textColor = UIColorBlack;
    _levelLabel.font = CodeFontMake(20);
    _levelLabel.contentEdgeInsets = UIEdgeInsetsMake(13, 15, 13, 15);
    _levelLabel.text = NSLocalizedString(@"water_level_1", nil);
    [_headerView addSubview:_levelLabel];
    
    _statusLabel = [[QMUILabel alloc] init];
    _statusLabel.font = CodeFontMake(16);
    _statusLabel.backgroundColor = kTextBGColor;
    _statusLabel.text = NSLocalizedString(@"state_standby", nil);
    [_headerView addSubview:_statusLabel];
    
    _imageView2 = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imageView2.backgroundColor = UIColorClear;
    _imageView2.image = UIImageMake(@"water_working");
    [_headerView addSubview:_imageView2];
    
    _waterBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_waterBtn setImage:UIImageMake(@"water_make") forState:UIControlStateNormal];
    [_waterBtn addTarget:self action:@selector(waterAction:) forControlEvents:UIControlEventTouchUpInside];
    _waterBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
    _waterBtn.layer.cornerRadius = 5.0f;
    [_headerView addSubview:_waterBtn];
    
    _powerBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_powerBtn setImage:UIImageMake(@"water_power") forState:UIControlStateNormal];
    [_powerBtn addTarget:self action:@selector(powerAction:) forControlEvents:UIControlEventTouchUpInside];
    _powerBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
    _powerBtn.layer.cornerRadius = 5.0f;
    [_headerView addSubview:_powerBtn];
    
    //Wave
    CGFloat waveHeight = 80.0f;
    CGFloat labelHeight = 40.0f;
    CGFloat imageBottom = 30.0f;
    if (IS_35INCH_SCREEN) {
        waveHeight = 40.0f;
        labelHeight = 30.0f;
        imageBottom = 26.0f;
    } else if (IS_58INCH_SCREEN) {
        waveHeight = 100.0f;
        imageBottom = 50.0f;
    }
    _waveView = [[WPWaveView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, waveHeight)];
    [_headerView addSubview:_waveView];
    
    _imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 12, waveHeight - imageBottom, 24, 24)];
    _imageView3.backgroundColor = UIColorClear;
    _imageView3.image = UIImageMake(@"water_arrow_up");
    [_waveView addSubview:_imageView3];
    
    _filterLabel = [[QMUILabel alloc] initWithFrame:CGRectMake(0, waveHeight - labelHeight, 100, labelHeight)];
    _filterLabel.textColor = UIColorGray9;
    _filterLabel.textAlignment = NSTextAlignmentCenter;
    _filterLabel.font = KKFontMake(16);
    _filterLabel.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
    _filterLabel.text = NSLocalizedString(@"title_filter_state", nil);
    [_waveView addSubview:_filterLabel];
    
    _sumLabel = [[QMUILabel alloc] initWithFrame:CGRectMake(100, waveHeight - labelHeight, SCREEN_WIDTH - 100, labelHeight)];
    _sumLabel.textColor = UIColorWhite;
    _sumLabel.textAlignment = NSTextAlignmentRight;
    _sumLabel.font = KKFontMake(16);
    _sumLabel.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
    _sumLabel.text = [NSString stringWithFormat:NSLocalizedString(@"sum_work_day", nil), 0];
    [_waveView addSubview:_sumLabel];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.mainColor = UIColorMakeWithHex(@"4898fa");
    
    [self.model getDeviceStatus:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (self.editingIndexPath) {
        [self configSwipeButtons];
    }
}

-(void)setupNavigationItems {
    
    self.title = [self.model deviceName];
    self.navRightImage = UIImageMake(@"icon_menu");
    
    [super setupNavigationItems];
}

-(CGFloat)cellHeight {
    return floor((SCREEN_HEIGHT - _imageView.qmui_height - _waveView.qmui_height - IPhoneXSafeAreaInsets.bottom) / 4);
}

#pragma mark - getter & setter
-(void)setMainColor:(UIColor *)mainColor {
    _mainColor = mainColor;
    
    _waveView.waveColor = mainColor;
    _powerBtn.backgroundColor = mainColor;
    _waterBtn.backgroundColor = mainColor;
    _backView.backgroundColor = mainColor;
    
    UIImage *backgroundImage = [QDUIHelper navigationBarBackgroundImageWithThemeColor:mainColor];
    [self.navigationController.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
}

-(void)setDataMap:(WPDataMap *)dataMap {
    _dataMap = dataMap;
    if (dataMap) {
        _imageView.image = [dataMap.data waterLevelImage];
        _levelLabel.text = [dataMap.data waterLevelTips];
        if (self.tableView.qmui_alreadyAtTop) {
            _statusLabel.attributedText = [WPData attributedStatusString:[dataMap.data statusString]];
        } else {
            _statusLabel.text = [dataMap.data statusString];
        }
        
        CGSize size = [_statusLabel sizeThatFits:_statusLabel.mj_size];
        _imageView2.qmui_left = _statusLabel.qmui_left + size.width - 10;
        
        self.mainColor = [dataMap.data waterLevelColor];
        
        _sumLabel.text = [NSString stringWithFormat:NSLocalizedString(@"sum_work_day", nil), dataMap.data.Worktime];
        
        if (dataMap.data.Switch == 1) {
            if (_offView) {
                [_offView removeFromSuperview];
                _offView = nil;
            }
            self.tableView.scrollEnabled = YES;
            self.tableView.allowsSelection = YES;
        } else {
            self.tableView.scrollEnabled = NO;
            self.tableView.allowsSelection = NO;
            
            self.offView.hidden = NO;
            [_headerView bringSubviewToFront:_waterBtn];
            [_headerView bringSubviewToFront:_powerBtn];
        }
        [self.tableView reloadData];
        
        self.filterAlertString = [dataMap.data stringForAlert];
    }
}

-(void)setFilterAlertString:(NSString *)filterAlertString {
    if (![_filterAlertString isEqualToString:filterAlertString]) {
        _filterAlertString = filterAlertString;
        NSString *message = [filterAlertString stringByAppendingString:NSLocalizedString(@"tips_change_filter", nil)];
        if(_filterAlert) {
            WS(ws);
            [_filterAlert dismissViewControllerAnimated:YES completion:^{
                ws.filterAlert = [KKAlert warningWithText:message];
            }];
        } else {
            self.filterAlert = [KKAlert warningWithText:message];
        }
    }
}

-(UIView *)offView {
    if (!_offView) {
        _offView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 2 * SCREEN_HEIGHT)];
        _offView.backgroundColor = [UIColorBlack colorWithAlphaComponent:0.6];
        [_headerView addSubview:_offView];
        
        CGFloat contentMinY = self.qmui_navigationBarMaxYInViewCoordinator;
        CGFloat Y = self.tableView.contentOffset.y + (contentMinY + self.imageView.qmui_height) / 2.0f;
        UIImageView *offIV = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 100, Y - 100, 200, 200)];
        offIV.image = UIImageMake(@"water_off");
        [_offView addSubview:offIV];
        
        QMUILabel *offLine = [[QMUILabel alloc] initWithFrame:CGRectMake(0, 90, 200, 20)];
        offLine.textColor = UIColorBlack;
        offLine.textAlignment = NSTextAlignmentCenter;
        offLine.text = NSLocalizedString(@"turned_off", nil);
        offLine.font = CodeFontMake(14);
        [offIV addSubview:offLine];
    }
    return _offView;
}

#pragma mark - Actions

-(void)powerAction:(id)sender {
    BOOL value = self.dataMap.data.Switch;
    [self.model send:@{ @"Switch": @(!value) }];
}

-(void)waterAction:(id)sender {
    BOOL value = self.dataMap.data.Wash;
    [self.model send:@{ @"Wash": @(!value) }];
}

-(void)rightAction {
    WS(ws);
    QMUIPopupMenuView *popupView = [[QMUIPopupMenuView alloc] init];
    popupView.preferLayoutDirection = QMUIPopupContainerViewLayoutDirectionBelow;
    popupView.automaticallyHidesWhenUserTap = YES;
    popupView.maximumWidth = 180;
    popupView.shouldShowItemSeparator = YES;
    popupView.separatorInset = UIEdgeInsetsMake(0, popupView.padding.left, 0, popupView.padding.right);
    
    UIImage *image1 = [UIImageMake(@"icon_edit") qmui_imageWithTintColor:_mainColor];
    QMUIPopupMenuItem *item1 = [QMUIPopupMenuItem itemWithImage:image1 title:NSLocalizedString(@"title_edit_name", nil) handler:^{
        [popupView hideWithAnimated:YES];
        
        [KKAlert inputWithTitle:NSLocalizedString(@"title_edit_name", nil) text:ws.model.deviceName placeholder:NSLocalizedString(@"tips_input_name", nil) ok:^(NSString *string) {
            
            [ws.model setCustomInfo:nil alias:string];
        }];
    }];
    [item1.button setTitleColor:_mainColor forState:UIControlStateNormal];
    popupView.items = @[ item1 ];
    [popupView layoutWithTargetRectInScreenCoordinate:CGRectMake(SCREEN_WIDTH - 30, self.qmui_navigationBarMaxYInViewCoordinator, 1, 1)];
    [popupView showWithAnimated:YES];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat contentMinY = self.qmui_navigationBarMaxYInViewCoordinator;
    
    _imageView.frame = CGRectMake(0, offsetY, SCREEN_WIDTH, floor(SCREEN_WIDTH * 25 / 27));
    
    offsetY += contentMinY;
    
    NSString *statusStr = _dataMap ? [_dataMap.data statusString] : NSLocalizedString(@"state_standby", nil);
    
    if (offsetY > 0) {
        if (offsetY > 50) {
            _levelLabel.frame = CGRectMake(0, _imageView.qmui_bottom - 50, SCREEN_WIDTH, 50);
            _levelLabel.backgroundColor = [kTextBGColor colorWithAlphaComponent:50 / 70.0f];
        } else {
            _levelLabel.backgroundColor = [kTextBGColor colorWithAlphaComponent:offsetY / 70.0f];
        }
        
        if (offsetY > 130) {
            _statusLabel.text = statusStr;
            _statusLabel.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 0, 15);
            _statusLabel.frame = CGRectMake(0, _imageView.qmui_bottom - 80, SCREEN_WIDTH, 30);
            _statusLabel.backgroundColor = [kTextBGColor colorWithAlphaComponent:130 / 182.0f];
            CGSize size = [_statusLabel sizeThatFits:_statusLabel.mj_size];
            _imageView2.frame = CGRectMake(_statusLabel.qmui_left + size.width - 10, _statusLabel.qmui_top + 10, 20, 20);
        } else {
            _statusLabel.backgroundColor = [kTextBGColor colorWithAlphaComponent:offsetY / 182.0f];
        }
        
        if (offsetY > 111) {
            _waterBtn.frame = CGRectMake(SCREEN_WIDTH - 90, _imageView.qmui_bottom - 141, 70, 70);
            _powerBtn.frame = CGRectMake(_waterBtn.qmui_left, _waterBtn.qmui_bottom + 1, 70, 70);
        }
        
        _waveView.qmui_bottom = _headerView.qmui_height;
        
        CGFloat progress = offsetY / (4 * [self cellHeight]);
        _imageView3.alpha = 1 - progress;
        _filterLabel.alpha = progress;
        _sumLabel.alpha = progress;
    } else {
        _imageView3.alpha = 1;
        _filterLabel.alpha = 0;
        _sumLabel.alpha = 0;
        
        _levelLabel.backgroundColor = kTextBGColor;
        _statusLabel.backgroundColor = [kTextBGColor colorWithAlphaComponent:0];
        
        _levelLabel.frame = CGRectMake(0, _imageView.qmui_bottom, SCREEN_WIDTH, 50);
        
        _statusLabel.contentEdgeInsets = UIEdgeInsetsMake(13, 15, 13, 15);
        _statusLabel.attributedText = [WPData attributedStatusString:statusStr];
        _statusLabel.frame = CGRectMake(0, _levelLabel.qmui_bottom, SCREEN_WIDTH, 50);
        CGSize size = [_statusLabel sizeThatFits:_statusLabel.mj_size];
        _imageView2.frame = CGRectMake(_statusLabel.qmui_left + size.width - 10, _statusLabel.qmui_top + 15, 20, 20);
        _waterBtn.frame = CGRectMake(SCREEN_WIDTH - 90, _imageView.qmui_bottom - 30, 70, 70);
        _powerBtn.frame = CGRectMake(_waterBtn.qmui_left, _waterBtn.qmui_bottom + 1, 70, 70);
        _waveView.qmui_bottom = _headerView.qmui_height + offsetY;
    }
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y + self.qmui_navigationBarMaxYInViewCoordinator;
    if (offsetY > 2 * [self cellHeight]) {
        [scrollView qmui_scrollToBottomAnimated:YES];
    } else {
        [scrollView qmui_scrollToTopAnimated:YES];
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self scrollViewWillBeginDecelerating:scrollView];
    }
}

#pragma mark - WPFilterCellDelegate
-(void)buyClicked:(WPFilterCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSString *urlString = [WPData filter_url:indexPath.row];
    if (indexPath.row == 2) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    } else {
        [NDSUD setObject:urlString forKey:@"kURLPrepareLoading"];
        [APP_DELEGATE.tabBarViewController setSelectedIndex:1];
    }
}

#pragma mark - UITableViewDataSource & UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self cellHeight];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WPFilterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL_ID1"];
    if (!cell) {
        cell = [[WPFilterCell alloc] initWithReuseIdentifier:@"CELL_ID1"];
        cell.delegate = self;
    }
    cell.imageView.image = [WPData filterImage:indexPath.row];
    cell.textLabel.text = [WPData filterString:indexPath.row];
    cell.lifeTime = [_dataMap.data filter_life:indexPath.row];
    cell.usedTime = [_dataMap.data filter_used:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    self.editingIndexPath = indexPath;
    [self.view setNeedsLayout];
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    self.editingIndexPath = nil;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WPFilterCell *cell = (WPFilterCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.shouldBuy) {
        WS(ws);
        UITableViewRowAction *resetAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:NSLocalizedString(@"action_reset", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            NSString *filter = [WPData filterString:indexPath.row];
            NSString *key = [WPData filterKey:indexPath.row];
            NSString *message = [NSString stringWithFormat:NSLocalizedString(@"tips_reset_filter", nil), filter];
            [KKAlert alertWithTitle:action.title message:message cancel:^{
                ;
            } ok:^{
                [ws.model send:@{ key: @0 }];
            }];
        }];
        resetAction.backgroundColor = _mainColor;
        return @[ resetAction ];
    }
    return @[];
}

- (void)configSwipeButtons {
    if (IOS_VERSION_NUMBER >= 110000) {
        for (UIView *subview in self.tableView.subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] && [subview.subviews count] >= 1) {
                subview.qmui_borderPosition = QMUIBorderViewPositionTop;
                UIButton *resetAction = subview.subviews[0];
                [self configDeleteButton:resetAction];
            }
        }
    } else {
        WPFilterCell *tableCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
        for (UIView *subview in tableCell.subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")] && [subview.subviews count] >= 1) {
                subview.qmui_borderPosition = QMUIBorderViewPositionTop;
                UIButton *resetAction = subview.subviews[0];
                [self configDeleteButton:resetAction];
            }
        }
    }
}

- (void)configDeleteButton:(UIButton *)resetAction {
    if (resetAction) {
        CGFloat superHeight = resetAction.superview.qmui_height;
        CGFloat resetHeight = superHeight < 40 ? 26 : 36;
        resetAction.titleLabel.font = CodeFontMake(14);
        resetAction.frame = CGRectMake(resetAction.qmui_left, (superHeight - resetHeight) / 2.0, 70, resetHeight);
        resetAction.backgroundColor = UIColorWhite;
        resetAction.layer.cornerRadius = resetHeight / 2.0f;
        resetAction.layer.masksToBounds = YES;
        [resetAction setTitleColor:_mainColor forState:UIControlStateNormal];
    }
}

#pragma mark - GizWifiDeviceDelegate

-(void)device:(GizWifiDevice *)device didSetCustomInfo:(NSError *)result {
    LOG(@"result %zi", result.code);
    if (result.code == GIZ_SDK_SUCCESS) {
        self.title = [self.model deviceName];
    } else {
        [KKHUD showError:NSLocalizedString(@"tips_failed", nil)];
    }
}

-(void)device:(GizWifiDevice *)device didUpdateNetStatus:(GizWifiDeviceNetStatus)netStatus {
    LOG(@"netStatus %zi",netStatus);
}

-(void)device:(GizWifiDevice *)device didReceiveData:(NSError *)result data:(NSDictionary<NSString *,id> *)dataMap withSN:(NSNumber *)sn {
    LOG(@"result %zi dataMap %@ sn %@", result.code, dataMap, sn);
    if (result.code == GIZ_SDK_SUCCESS) {
        self.dataMap = [WPDataMap mj_objectWithKeyValues:dataMap];
    }
}

-(void)device:(GizWifiDevice *)device didSetSubscribe:(NSError *)result isSubscribed:(BOOL)isSubscribed {
    LOG(@"result %zi isSubscribed %d", result.code, isSubscribed);
}

-(void)device:(GizWifiDevice *)device didGetHardwareInfo:(NSError *)result hardwareInfo:(NSDictionary<NSString *,NSString *> *)hardwareInfo {
    LOG(@"result %zi hardwareInfo %@", result.code, hardwareInfo);
}
@end
